﻿#include "FunctionForm.h"
#include "ui_FunctionForm.h"
#include "TimeEditForm.h"
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QMouseEvent>
#include <QTimer>
#include "common/Utils.h"
#include "common/GradientButton.h"
#include <QListView>

FunctionForm::FunctionForm(QWidget *parent) :
    QWidget(parent),m_Index(0),m_CurrentParagraph(20),m_CurrentParagraphEnable(true),
    ui(new Ui::FunctionForm),isRunState(false),isConState(false),isfaultState(false),
    offlineMap(":/res/image/Offline.png"),
    onlineMap(":/res/image/Online.png"),faultMap(":/res/image/faultState.png"),
    m_CSV_delay(0)
{
    ui->setupUi(this);
    ui->cbox_TimeShow->setView(new QListView(this));
    m_WaveForm = new WaveForm(this);
    m_WaveForm->hide();
    connect(m_WaveForm,&WaveForm::closeForm,this,&FunctionForm::slot_SubFormClose);

    //找出控件中所有的时间编辑控件
     QList<TimeEditForm*> timeEdits = this->findChildren<TimeEditForm*>();

     for (TimeEditForm* timeEdit : timeEdits) {
         //依据名称给每一个时间控件一个标识ID  成员变量index  连接槽函数区分使用
         QStringList nameStrList = timeEdit->objectName().split("_");
         if(nameStrList.size() == 2)
         {
             int index = nameStrList.at(1).toInt();
             timeEdit->setIndex(index);
         }

         // 修改时间显示格式的槽函数
         connect(this,&FunctionForm::sig_SetTimeFormat,timeEdit,&TimeEditForm::setTimeFormat);
         // 修改时间时触发到FunctionForm界面的槽函数
         connect(timeEdit,&TimeEditForm::sig_ValueChanged,this,&FunctionForm::slot_SecondsChanged);
     }

    //电流数值被改变的槽函数
     QRegularExpression regex1("doubleSpinBox_\\d+");
     QList<QDoubleSpinBox*> doubleSpinBoxs = this->findChildren<QDoubleSpinBox*>(regex1);
     for (QDoubleSpinBox* doubleSpinBox : doubleSpinBoxs) {
         connect(doubleSpinBox,SIGNAL(valueChanged(double)),this,SLOT(slot_EleCurrentChanged(double)));
     }

     QRegularExpression regex2("btnParEnable_\\d+");
     QList<QPushButton*> btnParEnables = this->findChildren<QPushButton*>(regex2);
     for (QPushButton* btnParEnable : btnParEnables) {
         connect(btnParEnable,SIGNAL(clicked(bool)),this,SLOT(slot_btnParEnable(bool)));
     }

     m_Settings = nullptr;

     //添加连接状态的显示log
     //ui->label_Link->setPixmap(offlineMap);

     ui->doubleSpinBox_EleCur->installEventFilter(this);
     ui->doubleSpinBox_EleVol->installEventFilter(this);

     //记录当前的时间
//     m_DateTimeCurrentPre = QDateTime::currentDateTime();
//     m_DateTimeVolPre = m_DateTimeCurrentPre;

     msgBox.setWindowTitle("是否切换？");

     msgBox.setIcon(QMessageBox::Information);

     // 创建 OK 和 Cancel 按钮
     QPushButton *okButton = msgBox.addButton("确认", QMessageBox::AcceptRole);
     QPushButton *cancelButton = msgBox.addButton("取消", QMessageBox::RejectRole);

     // 设置按钮大小
     QSize buttonSize(80, 30); // 宽度100，高度40
     okButton->setFixedSize(buttonSize);
     cancelButton->setFixedSize(buttonSize);

     ui->btn_Link->setIcon(offlineMap);
     ui->btnRun->setStyleSheet(BtnRunGray);
     this->setFocusPolicy(Qt::StrongFocus);


}

FunctionForm::~FunctionForm()
{
    if(m_File->isOpen())
        m_File->close();
    delete ui;
}

//更新ini文件并刷新界面数据
void FunctionForm::setSettings(int index,QSettings *settings)
{
    m_Index = index;
    if(m_Index != 1)
    {
        // 其他界面隐藏总复位
        ui->btnReset_2->setEnabled(false);
        ui->btnReset_2->setStyleSheet("background-color: transparent;color: transparent;");
    }

    // 隐藏一个按钮控件
    QSizePolicy retain = ui->btnUpdate->sizePolicy();   // 获取控件的大小调整策略
    retain.setRetainSizeWhenHidden(true);               // 设置控件被隐藏时，任然保持在布局中的位置大小
    ui->btnUpdate->setSizePolicy(retain);               // 重新设置大小策略
    ui->btnUpdate->hide();


    if(settings)
    {
        m_Settings = settings;
        //恢复界面的数值

        // 指定要读取的组 模式一的数据
        m_Settings->beginGroup(QString("Power%1_Mode1").arg(m_Index));

        for(int i = 1 ; i <= 20 ; i++)//20个段
        {
            // 读取使 设置时间 和  电流
            QString KeyTime = QString("paragraph%1_Time").arg(i);
            QString KeyEleCurrent = QString("paragraph%1_EleCurrent").arg(i);

            //读取设置的时间
            TimeEditForm*  timeEditForm = this->findChild<TimeEditForm*>(QString("TimeEdit_%1").arg(i));
            if(timeEditForm)
            {
                timeEditForm->blockSignals(true);
                timeEditForm->setValue(m_Settings->value(KeyTime,0).toInt());
                timeEditForm->blockSignals(false);
            }

            //读取设置电流
            QDoubleSpinBox*  doubleSpinBox = this->findChild<QDoubleSpinBox*>(QString("doubleSpinBox_%1").arg(i));
            if(doubleSpinBox)
            {
                doubleSpinBox->blockSignals(true);
                doubleSpinBox->setValue(m_Settings->value(KeyEleCurrent,0.0).toDouble());
                doubleSpinBox->blockSignals(false);
            }
        }

        // 结束组的读取
        m_Settings->endGroup();

        // 指定要读取的组 模式二的数据
        m_Settings->beginGroup(QString("Power%1_Mode2").arg(m_Index));
        // 读取开始时间、结束时间和循环次数 起始电流
        quint64 tempTime1 = m_Settings->value("StartTime",0).toULongLong();
        quint64 tempTime2 = m_Settings->value("EndTime",0).toULongLong();
        quint64 tempTime3 = m_Settings->value("Repetitions",0).toULongLong();
        quint64 tempTime33 = m_Settings->value("Remain",0).toULongLong();


        double tempTime4 = m_Settings->value("StartEleCurrent",0.0).toDouble();

        ui->TimeEditStart_21->blockSignals(true);
        ui->TimeEditEnd_22->blockSignals(true);
        ui->spinBox_Repetitions->blockSignals(true);
        // ui->spinBox_Remain->blockSignals(true);
        ui->dSpinBox_startElecurrent->blockSignals(true);

        ui->TimeEditStart_21->setValue(tempTime1);
        ui->TimeEditEnd_22->setValue(tempTime2);
        ui->spinBox_Repetitions->setValue(tempTime3);
        // ui->spinBox_Remain->setValue(tempTime33);
        ui->dSpinBox_startElecurrent->setValue(tempTime4);

        ui->TimeEditStart_21->blockSignals(false);
        ui->TimeEditEnd_22->blockSignals(false);
        ui->spinBox_Repetitions->blockSignals(false);
        // ui->spinBox_Remain->blockSignals(true);
        ui->dSpinBox_startElecurrent->blockSignals(false);

        // 结束组的读取
        m_Settings->endGroup();

        // 指定要读取的其他参数
        m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
        ui->doubleSpinBoxCurValue->blockSignals(true);
        ui->doubleSpinBoxVolValue->blockSignals(true);
        ui->cbox_TimeShow->blockSignals(true);
        ui->doubleSpinBoxCurValue->setValue(m_Settings->value("EleCurrentRange",0.0).toDouble());
        ui->doubleSpinBoxVolValue->setValue(m_Settings->value("EleVolRange",0.0).toDouble());
        bool hhmmss = m_Settings->value("TimeShow_hhmmss").toBool();
        ui->doubleSpinBoxCurValue->blockSignals(false);
        ui->doubleSpinBoxVolValue->blockSignals(false);
        ui->cbox_TimeShow->blockSignals(false);

        m_CurrentMode = m_Settings->value("CurrentMode",1).toInt();
        switch (m_CurrentMode) {
        case 1:
            ui->btnMode_1->setChecked(true);
            break;
        case 2:
            ui->btnMode_2->setChecked(true);
            break;
        case 3:
            ui->btnMode_3->setChecked(true);
            break;
        default:
            break;
        }

        m_CurrentParagraph = m_Settings->value("CurrentParagraph",1).toInt();                 //当前的段， int
        m_CurrentParagraphEnable = m_Settings->value("CurrentParagraphEnable",true).toBool(); //当前的段使能  bool

        m_eleCurrentRange = m_Settings->value("EleCurrentRange",0.0).toFloat();
        m_eleVolRange = m_Settings->value("EleVolRange",0.0).toFloat();
        setCurrentParagraphEnable(m_CurrentParagraph,m_CurrentParagraphEnable,true);


        // 结束组的读取
        m_Settings->endGroup();

        if(ui->cbox_TimeShow->count() >=2)
        {
            if(hhmmss)
            {
                emit sig_SetTimeFormat(0);
                ui->cbox_TimeShow->setCurrentIndex(0);
            }
            else
            {
                emit sig_SetTimeFormat(1);
                ui->cbox_TimeShow->setCurrentIndex(1);
            }
        }
    }

    /****************创建电流电压存CSV的功能*********************/
   m_timer_CSV = new QTimer(this);
   connect(m_timer_CSV,&QTimer::timeout,this,&FunctionForm::timeoutWatchDog);

   m_timer_CSV_delay = new QTimer(this);
   connect(m_timer_CSV_delay,&QTimer::timeout,this,&FunctionForm::timeoutWatchDog_delay);

   //是否打开定时器
   if(isRunState)
   {
       if(!ui->btnEleCurCSV->isChecked())
           ui->btnEleCurCSV->setChecked(true);
       if(!ui->btnEleVolCSV->isChecked())
           ui->btnEleVolCSV->setChecked(true);
       m_timer_CSV->start(3000);//一秒一次写入
   }
   else
   {
       if(ui->btnEleCurCSV->isChecked())
           ui->btnEleCurCSV->setChecked(false);
       if(ui->btnEleVolCSV->isChecked())
           ui->btnEleVolCSV->setChecked(false);
   }

   //当前路径下自动保存数据的文件夹
   QString folderName = "AutoSaveData";
   QString folderPath = QDir(QCoreApplication::applicationDirPath()).filePath(folderName);
   QDir dir(folderPath);

   if (!dir.exists()) {
       if (dir.mkdir(".")) {
           qDebug() << "文件夹创建成功：" << folderPath;
       } else {
           qDebug() << "文件夹创建失败";
       }
   } else {
       qDebug() << "文件夹已存在：" << folderPath;
   }

   // 获取并输出文件夹路径
   qDebug() << "文件夹路径：" << folderPath;

   //当前路径下自动保存数据的文件夹的日期分类
   QString folderDateName = QDateTime::currentDateTime().toString("yyyy_MM_dd");
   QString folderDatePath = QDir(folderPath).filePath(folderDateName);
   QDir DateDir(folderDatePath);

   if (!DateDir.exists()) {
       if (DateDir.mkdir(".")) {
           qDebug() << "日期文件夹创建成功：" << folderDatePath;
       } else {
           qDebug() << "日期文件夹创建失败";
       }
   } else {
       qDebug() << "日期文件夹已存在：" << folderDatePath;
   }



   // 获取当前应用程序的路径
   QString filePath = folderDatePath + "/" + QDateTime::currentDateTime().toString("yyyyMMdd_") + QString("Power_%1.csv").arg(m_Index);

   // 创建文件
   m_File = new QFile(filePath);

   // 检查文件是否存在
   if (!m_File->exists())//如果文件不存在则创建文件
   {
       if (!m_File->open(QIODevice::WriteOnly | QIODevice::Text)) {
           qDebug() << "无法打开或创建文件：" << filePath;
       }
       else // 打开文件写入默认表头
       {
           m_File->write(QString("电源%1\n").arg(m_Index).toUtf8());
           m_File->write(QString("表格创建时间：%1\n").arg(QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss")).toUtf8());
           m_File->write(QString("时间,电流,电压,备注\n").toUtf8());
       }
   }
   else                 //文件存在则追加打开
   {
       if (!m_File->open(QIODevice::Append | QIODevice::Text))
       {
           qDebug() << "追加打开文件失败：" << filePath;
       }
   }

   // 创建文本流
   m_Out  = new QTextStream(m_File);
   m_Out->setCodec("UTF-8");

}

//设置大电源
void FunctionForm::setBigPower()
{
    //电流数值被改变的槽函数
    QRegularExpression regex1("doubleSpinBox_\\d+");
    QList<QDoubleSpinBox*> doubleSpinBoxs = this->findChildren<QDoubleSpinBox*>(regex1);
    for (QDoubleSpinBox* doubleSpinBox : qAsConst(doubleSpinBoxs)) {
        doubleSpinBox->setMaximum(50.00);
    }
    ui->dSpinBox_startElecurrent->setMaximum(50.00);
}

int FunctionForm::getIndex()
{
    return m_Index;
}

void FunctionForm::ReSetTings(QSettings *settings)
{
    if(settings)
    {
        m_Settings = settings;


        // printAllSettings(m_Settings);

        //恢复界面的数值

        // 指定要读取的组 模式一的数据
        m_Settings->beginGroup(QString("Power%1_Mode1").arg(m_Index));

        for(int i = 1 ; i <= 20 ; i++)//20个段
        {
            // 读取使 设置时间 和  电流
            QString KeyTime = QString("paragraph%1_Time").arg(i);
            QString KeyEleCurrent = QString("paragraph%1_EleCurrent").arg(i);

            //读取设置的时间
            TimeEditForm*  timeEditForm = this->findChild<TimeEditForm*>(QString("TimeEdit_%1").arg(i));
            if(timeEditForm)
            {
                timeEditForm->blockSignals(true);
                timeEditForm->setValue(m_Settings->value(KeyTime,0).toInt());
                timeEditForm->blockSignals(false);
            }

            //读取设置电流
            QDoubleSpinBox*  doubleSpinBox = this->findChild<QDoubleSpinBox*>(QString("doubleSpinBox_%1").arg(i));
            if(doubleSpinBox)
            {
                doubleSpinBox->blockSignals(true);
                doubleSpinBox->setValue(m_Settings->value(KeyEleCurrent,0.0).toDouble());
                doubleSpinBox->blockSignals(false);
            }
        }

        // 结束组的读取
        m_Settings->endGroup();

        // 指定要读取的组 模式二的数据
        m_Settings->beginGroup(QString("Power%1_Mode2").arg(m_Index));
        // 读取开始时间、结束时间和循环次数 起始电流
        quint64 tempTime1 = m_Settings->value("StartTime",0).toULongLong();
        quint64 tempTime2 = m_Settings->value("EndTime",0).toULongLong();
        quint64 tempTime3 = m_Settings->value("Repetitions",0).toULongLong();
        quint64 tempTime33 = m_Settings->value("Remain",0).toULongLong();


        double tempTime4 = m_Settings->value("StartEleCurrent",0.0).toDouble();

        ui->TimeEditStart_21->blockSignals(true);
        ui->TimeEditEnd_22->blockSignals(true);
        ui->spinBox_Repetitions->blockSignals(true);
        // ui->spinBox_Remain->blockSignals(true);
        ui->dSpinBox_startElecurrent->blockSignals(true);

        ui->TimeEditStart_21->setValue(tempTime1);
        ui->TimeEditEnd_22->setValue(tempTime2);
        ui->spinBox_Repetitions->setValue(tempTime3);
        // ui->spinBox_Remain->setValue(tempTime33);
        ui->dSpinBox_startElecurrent->setValue(tempTime4);

        ui->TimeEditStart_21->blockSignals(false);
        ui->TimeEditEnd_22->blockSignals(false);
        ui->spinBox_Repetitions->blockSignals(false);
        // ui->spinBox_Remain->blockSignals(true);
        ui->dSpinBox_startElecurrent->blockSignals(false);

        // 结束组的读取
        m_Settings->endGroup();

        // 指定要读取的其他参数
        m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
        ui->doubleSpinBoxCurValue->blockSignals(true);
        ui->doubleSpinBoxVolValue->blockSignals(true);
        ui->cbox_TimeShow->blockSignals(true);
        ui->doubleSpinBoxCurValue->setValue(m_Settings->value("EleCurrentRange",0.0).toDouble());
        ui->doubleSpinBoxVolValue->setValue(m_Settings->value("EleVolRange",0.0).toDouble());
        bool hhmmss = m_Settings->value("TimeShow_hhmmss").toBool();
        ui->doubleSpinBoxCurValue->blockSignals(false);
        ui->doubleSpinBoxVolValue->blockSignals(false);
        ui->cbox_TimeShow->blockSignals(false);

        m_CurrentMode = m_Settings->value("CurrentMode",1).toInt();
        switch (m_CurrentMode) {
        case 1:
            ui->btnMode_1->setChecked(true);
            break;
        case 2:
            ui->btnMode_2->setChecked(true);
            break;
        case 3:
            ui->btnMode_3->setChecked(true);
            break;
        default:
            break;
        }

        m_CurrentParagraph = m_Settings->value("CurrentParagraph",1).toInt();                 //当前的段， int
        m_CurrentParagraphEnable = m_Settings->value("CurrentParagraphEnable",true).toBool(); //当前的段使能  bool

        m_eleCurrentRange = m_Settings->value("EleCurrentRange",0.0).toFloat();
        m_eleVolRange = m_Settings->value("EleVolRange",0.0).toFloat();
        setCurrentParagraphEnable(m_CurrentParagraph,m_CurrentParagraphEnable,true);


        // 结束组的读取
        m_Settings->endGroup();

        if(ui->cbox_TimeShow->count() >=2)
        {
            if(hhmmss)
            {
                emit sig_SetTimeFormat(0);
                ui->cbox_TimeShow->setCurrentIndex(0);
            }
            else
            {
                emit sig_SetTimeFormat(1);
                ui->cbox_TimeShow->setCurrentIndex(1);
            }
        }
    }
}

//设置运行状态
void FunctionForm::setRunState(bool isRun)
{
    isRunState = isRun;
    if(isRunState)
    {
        ui->btnRun->setStyleSheet(BtnRunBlue);
        //最后修改为运行时 可修改参数，所以无需禁用编辑
        // disableAllChildWidgets(ui->groupBox_1,false);
        // disableAllChildWidgets(ui->groupBox_2,false);
        ui->btnUpdate->show();
        if(!m_timer_CSV->isActive())
        {
            m_timer_CSV_delay->stop();
            m_timer_CSV->start(3000);//3秒一次写入
        }
        if(!ui->btnEleCurCSV->isChecked())
            ui->btnEleCurCSV->setChecked(true);
        if(!ui->btnEleVolCSV->isChecked())
            ui->btnEleVolCSV->setChecked(true);
    }
    else
    {
        ui->btnRun->setStyleSheet(BtnRunGray);
        //最后修改为运行时 可修改参数，所以无需禁用编辑
        // disableAllChildWidgets(ui->groupBox_1,true);
        // disableAllChildWidgets(ui->groupBox_2,true);
        ui->btnUpdate->hide();
        if(m_timer_CSV->isActive())
        {
            m_timer_CSV->stop();
            if(isfaultState)//是否总故障报停
            {
                timeoutWatchDog_delay();
                m_timer_CSV_delay->start(3000);
            }
        }
        if(ui->btnEleCurCSV->isChecked())
            ui->btnEleCurCSV->setChecked(false);
        if(ui->btnEleVolCSV->isChecked())
            ui->btnEleVolCSV->setChecked(false);
    }
}

//设置连接状态
void FunctionForm::setConnectionState(bool isConnectionState)
{
    isConState = isConnectionState;
    if(isConState)
    {
        ui->btn_Link->setIcon(onlineMap);
    }
    else
    {
        ui->btn_Link->setIcon(offlineMap);
        //emit sig_SetRunState(false,m_Index,true);//停用当前运行

        //运行和禁用置回去
        //ui->btnRun->setStyleSheet(BtnRunGray);
        //disableAllChildWidgets(ui->groupBox_1,true);
        //disableAllChildWidgets(ui->groupBox_2,true);

        if(m_timer_CSV->isActive())
            m_timer_CSV->stop();
        if(ui->btnEleCurCSV->isChecked())
            ui->btnEleCurCSV->setChecked(false);
        if(ui->btnEleVolCSV->isChecked())
            ui->btnEleVolCSV->setChecked(false);
    }
    setDisconnectForRun(isConState);

}

//设置故障的状态
void FunctionForm::setFaultState(bool faultState)
{
    isfaultState = faultState;
    if(isfaultState)
    {
        ui->lab_FaultState->setPixmap(faultMap);
        sig_showMessage(QString("电源%1 总故障报错").arg(m_Index));
    }
    else
    {
        // 移除QLabel中的图片
        ui->lab_FaultState->setPixmap(QPixmap());
    }
}

void FunctionForm::setCurFaultState(bool faultState) //设置电流故障状态、
{
    ui->btnFaultState_1->setChecked(faultState);
}

void FunctionForm::setVolFaultState(bool faultState) //设置电压故障状态、
{
    ui->btnFaultState_2->setChecked(faultState);
}

void FunctionForm::setTempFaultState(bool faultState) //设置温度故障状态、
{
    ui->btnFaultState_3->setChecked(faultState);
}

//设置电流
void FunctionForm::setEleCurrentValue(float fEleCurrent)
{
    ui->doubleSpinBox_EleCur->setValue(fEleCurrent);
}

//设置电压
void FunctionForm::setEleVolValue(float fEleVol)
{
    ui->doubleSpinBox_EleVol->setValue(fEleVol);
}

//设置剩余次数 模式2和模式三
void FunctionForm::setReMainValue(int iReMain1,int iReMain2)
{
    if(isRunState)
    {
        ui->spinBox_Remain->setValue( ui->spinBox_Repetitions->value() - iReMain1);
        ui->spinBox_Remain_2->setValue(ui->spinBox_Repetitions->value() - iReMain2);
    }
}

void FunctionForm::setScreenSize(QSize size)
{
    m_ScreenSize = size;
}

void FunctionForm::setWriteCSV(bool isWrite)
{
    if(isWrite)
    {
        if(isRunState)//在运行状态则打开写CSV
        {
            if(!m_timer_CSV->isActive())
                m_timer_CSV->start(3000);//3秒一次写入
            if(!ui->btnEleCurCSV->isChecked())
                ui->btnEleCurCSV->setChecked(true);
            if(!ui->btnEleVolCSV->isChecked())
                ui->btnEleVolCSV->setChecked(true);
        }
    }
}

void FunctionForm::setDisconnectForRun(bool isDisconnect)
{
    if(isDisconnect)
    {
        if(isRunState)//运行中断开
        {
            ui->btnRun->setStyleSheet(BtnRunGray);
            //最后修改为运行时 可修改参数，所以无需禁用编辑
            // disableAllChildWidgets(ui->groupBox_1,true);
            // disableAllChildWidgets(ui->groupBox_2,true);
        }
    }
    else//恢复连接
    {
        ui->btnRun->setStyleSheet(BtnRunGray);
        //最后修改为运行时 可修改参数，所以无需禁用编辑
        // disableAllChildWidgets(ui->groupBox_1,true);
        // disableAllChildWidgets(ui->groupBox_2,true);
    }

}

void FunctionForm::setGroupBoxTitleText(bool isShow)
{
    if(isShow)
    {
        ui->lab_title_1->hide();
        ui->groupBox_1->setTitle("模式一");
        ui->lab_title_2->hide();
        ui->groupBox_2->setTitle("模式二");
        ui->lab_title_3->hide();
        ui->groupBox_3->setTitle("数据显示");
        ui->lab_title_4->hide();
        ui->groupBox_4->setTitle("故障信息");
        ui->lab_title_5->hide();
        ui->groupBox_5->setTitle("数据参数保存");
        ui->horizontalLayout_2->setContentsMargins(0, 0, 0, 9);
        ui->horizontalLayout_3->setContentsMargins(0, 0, 0, 9);
    }
    else
    {
        ui->lab_title_1->show();
        ui->groupBox_1->setTitle("");
        ui->lab_title_2->show();
        ui->groupBox_2->setTitle("");
        ui->lab_title_3->show();
        ui->groupBox_3->setTitle("");
        ui->lab_title_4->show();
        ui->groupBox_4->setTitle("");
        ui->lab_title_5->show();
        ui->groupBox_5->setTitle("");
        ui->horizontalLayout_2->setContentsMargins(0, 9, 0, 9);
        ui->horizontalLayout_3->setContentsMargins(0, 9, 0, 9);
    }
}

void FunctionForm::slot_SecondsChanged(int index, quint64 seconds)
{
    qDebug() << "index:" << index << "  seconds:" << seconds;
    if(index >= 1 && index <= 20)
    {
        // 指定要读取的组 模式一的数据
        m_Settings->beginGroup(QString("Power%1_Mode1").arg(m_Index));

        QString KeyTime = QString("paragraph%1_Time").arg(index);
        m_Settings->setValue(KeyTime,seconds);

        // 结束组的读取
        m_Settings->endGroup();
    }
    else if(index == 21)
    {
        m_Settings->beginGroup(QString("Power%1_Mode2").arg(m_Index));
        m_Settings->setValue("StartTime",seconds);
        m_Settings->endGroup();
    }
    else if(index == 22)
    {
        m_Settings->beginGroup(QString("Power%1_Mode2").arg(m_Index));
        m_Settings->setValue("EndTime",seconds);
        m_Settings->endGroup();
    }
}

void FunctionForm::slot_EleCurrentChanged(double value)
{
    QObject* senderObj = sender(); // 获取发送信号的 QObject
    QStringList  nameStrList =  senderObj->objectName().split("_");
    if(nameStrList.size() == 2)
    {
        m_Settings->beginGroup(QString("Power%1_Mode1").arg(m_Index));
        m_Settings->setValue(QString("paragraph%1_EleCurrent").arg(nameStrList.at(1).toDouble()),value);
        m_Settings->endGroup();
    }
}

void FunctionForm::slot_btnParEnable(bool isClicked)
{
    QObject* senderObj = sender(); // 获取发送信号的 QObject
    QStringList  nameStrList =  senderObj->objectName().split("_");
    if(nameStrList.size() == 2)
    {
        //区分是哪一个段
        int paragraph = nameStrList.at(1).toInt();
        setCurrentParagraphEnable(paragraph,isClicked);
    }
}


void FunctionForm::on_cbox_TimeShow_currentIndexChanged(int index)
{
    emit sig_SetTimeFormat(index);
    m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
    switch (index) {
    case 0:
        m_Settings->setValue("TimeShow_hhmmss",true);
        break;
    case 1:
        m_Settings->setValue("TimeShow_hhmmss",false);
        break;
    default:
        break;
    }
    m_Settings->endGroup();
}

//设置循环次数
void FunctionForm::on_spinBox_Repetitions_valueChanged(int arg1)
{
    m_Settings->beginGroup(QString("Power%1_Mode2").arg(m_Index));
    m_Settings->setValue("Repetitions",arg1);
    m_Settings->endGroup();
}

/*
void FunctionForm::on_spinBox_Remain_valueChanged(int arg1)
{
    m_Settings->beginGroup(QString("Power%1_Mode2").arg(m_Index));
    m_Settings->setValue("Remain",arg1);
    m_Settings->endGroup();
}
*/

//设置起始电流
void FunctionForm::on_dSpinBox_startElecurrent_valueChanged(double arg1)
{
    m_Settings->beginGroup(QString("Power%1_Mode2").arg(m_Index));
    m_Settings->setValue("StartEleCurrent",arg1);
    m_Settings->endGroup();
}

//电流超值设置
void FunctionForm::on_btnCurValue_clicked()
{
    m_eleCurrentRange = ui->doubleSpinBoxCurValue->value();
    //1.发送超值的电流
    QList<quint16> sendData1;
    sendData1.append(floatToQuint16(m_eleCurrentRange));

    WriteData* writeData1 = new WriteData(3170+((m_Index-1)*2),sendData1.size(),sendData1);
    emit sig_AddWriteQueue(writeData1);

    //emit sig_SetWriteStartAddressAndRegisterCount(3170+((m_Index-1)*2),2,sendData1);
    QTimer::singleShot(40,[=]()
    {
        if(writeData1 != nullptr)
        emit sig_AddWriteQueue(writeData1);
        //emit sig_SetWriteStartAddressAndRegisterCount(3170+((m_Index-1)*2),2,sendData1);
    });

    m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
    m_Settings->setValue("EleCurrentRange",m_eleCurrentRange);
    m_Settings->endGroup();

}


void FunctionForm::on_btnSaveCSV_clicked()//保存到CSV
{
    QString fileName = QString("SaveData_").arg(m_Index);
    fileName += QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss");
    fileName += ".ini";

    QString filePath = QFileDialog::getSaveFileName(nullptr, "保存到ini文件中",fileName, "ini Files (*.ini);;All Files (*)");

    // 检查用户是否选择了文件
    if (filePath.isEmpty()) {
        qDebug() << "No file selected.";
        return;
    }

    saveSettingsToNewPath(m_Settings,filePath);

    /*
    // 创建文件选择对话框
    QString fileName = QString("电源%1_").arg(m_Index);
    fileName += QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss");
    fileName += ".csv";

    QString filePath = QFileDialog::getSaveFileName(nullptr, "保存到CSV文件中",fileName, "CSV Files (*.csv);;All Files (*)");

    // 检查用户是否选择了文件
    if (filePath.isEmpty()) {
        qDebug() << "No file selected.";
        return;
    }

    // 创建并打开文件
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "打开CSV文件失败";
        return;
    }

    // 创建文本流并写入CSV数据
    QTextStream out(&file);
    out << QString("电源%1保存时间：,").arg(m_Index) << QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss") << "\n";
    out << "\n";
    out << "\n";
    out << QString("模式一：\n");

    out   << QString(",第一段,第二段,第三段,第四段,第五段,第六段,第七段,第八段,第九段,第十段,第十一段,第十二段,第十三段,第十四段,第十五段,第十六段,第十七段,第十八段,第十九段,第二十段\n");

    QString timeSet("时间设置,");
    QString eleCurrentSet("电流设置,");
    for(int i = 1 ; i <= 20 ; i++)
    {
        TimeEditForm*  timeEditForm = this->findChild<TimeEditForm*>(QString("TimeEdit_%1").arg(i));
        if(timeEditForm)
        {
            timeSet += QString::number(timeEditForm->value());
            timeSet += ",";
        }

        QDoubleSpinBox*  doubleSpinBox = this->findChild<QDoubleSpinBox*>(QString("doubleSpinBox_%1").arg(i));
        if(doubleSpinBox)
        {
            eleCurrentSet += QString::number(doubleSpinBox->value(),'f',2);
            eleCurrentSet += ",";
        }
    }
    timeSet.chop(1);
    eleCurrentSet.chop(1);
    timeSet += "\n";
    eleCurrentSet += "\n";

    out   << timeSet;
    out   << eleCurrentSet;

    out   << "\n";
    out  << QString("模式二：\n");

    QString startTime("开通时间,");
    startTime += QString::number(ui->TimeEditStart_21->value(),'f',2);
    startTime += "\n";

    QString endTime("关闭时间,");
    endTime += QString::number(ui->TimeEditEnd_22->value(),'f',2);
    endTime += "\n";

    QString Repetitions("重复次数设置,");
    Repetitions += QString::number(ui->spinBox_Repetitions->value());
    Repetitions += "\n";

    out << startTime;
    out << endTime;
    out << Repetitions;

    // 关闭文件
    file.close();
    */
}

void FunctionForm::on_btnLoadCSV_clicked()
{
    QStringList filters;
    filters << "INI files (*.ini)" << "所有文件 (.)";
    QString selectedFilter;
    QString filePath = QFileDialog::getOpenFileName(nullptr, "选择ini文件", "", filters.join(";;"), &selectedFilter);
    if (filePath.isEmpty())
        return;
    qDebug() << "选择的文件路径:" << filePath;

    QSettings* tempSettings = new QSettings(filePath,QSettings::IniFormat);

    emit sig_ReSetIniFlie(tempSettings);


    /*
    if (!filePath.isEmpty()) {
        qDebug() << "选择的文件路径:" << filePath;

        QFile file(filePath);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            int lineNumber = 0;

            // 读取文件，直到第7行
            QList<int>  lineNum;
            lineNum << 6 << 7 << 9 << 10 <<11;

            while (!in.atEnd()) {
                ++lineNumber;
                QString line = in.readLine();

                switch (lineNumber) {
                case 6:
                {
                    qDebug() << "读取行:" << line;
                    QStringList lineListStr = line.split(",");
                    if(lineListStr.size() == 21)
                    {
                        for(int i = 1 ; i <= 20 ; i++)
                        {
                            TimeEditForm*  timeEditForm = this->findChild<TimeEditForm*>(QString("TimeEdit_%1").arg(i));
                            if(timeEditForm)
                            {
                                timeEditForm->setValue(lineListStr.at(i).toLongLong());
                            }
                        }
                    }
                    else
                    {
                        // 创建一个信息提示框
                        QMessageBox::information(nullptr, "信息提示", "导入的文件内容不正确");
                        break;
                    }
                }
                    break;
                case 7:
                {
                    QStringList lineListStr = line.split(",");
                    if(lineListStr.size() == 21)
                    {
                        for(int i = 1 ; i <= 20 ; i++)
                        {
                            QDoubleSpinBox*  doubleSpinBox = this->findChild<QDoubleSpinBox*>(QString("doubleSpinBox_%1").arg(i));
                            if(doubleSpinBox)
                            {
                                doubleSpinBox->setValue(lineListStr.at(i).toDouble());
                            }
                        }
                    }
                    else
                    {
                        // 创建一个信息提示框
                        QMessageBox::information(nullptr, "信息提示", "导入的文件内容不正确");
                        break;
                    }
                }
                    break;
                case 10:
                {
                    qDebug() << "读取行:" << line;
                    QStringList lineListStr = line.split(",");
                    if(lineListStr.size() == 2)
                    {
                        ui->TimeEditStart_21->setValue(lineListStr.at(1).toLongLong());
                    }
                    else
                    {
                        // 创建一个信息提示框
                        QMessageBox::information(nullptr, "信息提示", "导入的文件内容不正确");
                        break;
                    }
                }
                    break;
                case 11:
                {
                    qDebug() << "读取行:" << line;
                    QStringList lineListStr = line.split(",");
                    if(lineListStr.size() == 2)
                    {
                        ui->TimeEditEnd_22->setValue(lineListStr.at(1).toLongLong());
                    }
                    else
                    {
                        // 创建一个信息提示框
                        QMessageBox::information(nullptr, "信息提示", "导入的文件内容不正确");
                        break;
                    }
                }
                    break;
                case 12:
                {
                    qDebug() << "读取行:" << line;
                    QStringList lineListStr = line.split(",");
                    if(lineListStr.size() == 2)
                    {
                        ui->spinBox_Repetitions->setValue(lineListStr.at(1).toInt());
                    }
                    else
                    {
                        // 创建一个信息提示框
                        QMessageBox::information(nullptr, "信息提示", "导入的文件内容不正确");
                        break;
                    }
                }
                    break;

                default:
                    break;
                }
                // 在这里可以进一步处理每一行的数据
            }
            file.close();
        } else {
            qDebug() << "无法打开文件:" << filePath;
        }
    }
*/
}

bool FunctionForm::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *> (event);
        //qDebug()<<watched->objectName();
        if(mouseEvent->button() == Qt::LeftButton)
        {
            if(watched==ui->doubleSpinBox_EleCur || ui->doubleSpinBox_EleVol)
            {

                int x = (m_ScreenSize.width() - m_WaveForm->width() ) / 2;
                int y = (m_ScreenSize.height() - m_WaveForm->height() ) / 2;

                // 将子窗口移动到屏幕中心
                m_WaveForm->move(x, y);

                if(m_WaveForm->isHidden())
                    m_WaveForm->exec();
                qDebug() << "QMouseEvent cliecked";
            }
        }
    }

    else if(event->type() == QEvent::FocusIn)
    {
        if(watched==ui->doubleSpinBox_EleCur || watched==ui->doubleSpinBox_EleVol )
        {
            int x = (m_ScreenSize.width() - m_WaveForm->width() ) / 2;
            int y = (m_ScreenSize.height() - m_WaveForm->height() ) / 2;

            // 将子窗口移动到屏幕中心
            m_WaveForm->move(x, y);
            if(m_WaveForm->isHidden())
                m_WaveForm->exec();

        }
    }

    return QObject::eventFilter(watched,event);
}

//开关段落
void FunctionForm::setCurrentParagraphEnable(int CurrentParagraph, bool Enable,bool isInit)
{
    for(int i = 1; i < CurrentParagraph; i ++)
    {
        TimeEditForm*  timeEditForm = this->findChild<TimeEditForm*>(QString("TimeEdit_%1").arg(i));
        QDoubleSpinBox*  doubleSpinBox = this->findChild<QDoubleSpinBox*>(QString("doubleSpinBox_%1").arg(i));
        QPushButton*  btnParEnables = this->findChild<QPushButton*>(QString("btnParEnable_%1").arg(i));
        if(timeEditForm)
            timeEditForm->setEnabled(true);
        if(doubleSpinBox)
            doubleSpinBox->setEnabled(true);
        if(btnParEnables)
            btnParEnables->setChecked(true);
    }

    for(int i = CurrentParagraph; i <= 20; i ++)
    {
        TimeEditForm*  timeEditForm = this->findChild<TimeEditForm*>(QString("TimeEdit_%1").arg(i));
        QDoubleSpinBox*  doubleSpinBox = this->findChild<QDoubleSpinBox*>(QString("doubleSpinBox_%1").arg(i));
        QPushButton*  btnParEnables = this->findChild<QPushButton*>(QString("btnParEnable_%1").arg(i));
        if(Enable)
        {
            if(timeEditForm)
                timeEditForm->setEnabled(true);
            if(doubleSpinBox)
                doubleSpinBox->setEnabled(true);
            if(btnParEnables)
                btnParEnables->setChecked(true);
        }
        else
        {
            if(timeEditForm)
                timeEditForm->setEnabled(false);
            if(doubleSpinBox)
                doubleSpinBox->setEnabled(false);
            if(btnParEnables)
                btnParEnables->setChecked(false);
        }
    }

    if(!isInit)//如果不是初始化则写Ini
    {
        m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
        m_Settings->setValue("CurrentParagraph",CurrentParagraph);         //当前的段， int
        m_Settings->setValue("CurrentParagraphEnable",Enable);//当前的段使能  bool
        m_Settings->endGroup();
        m_CurrentParagraph = CurrentParagraph;
        m_CurrentParagraphEnable = Enable;

        QList<quint16>  sendData;
        if(m_CurrentParagraphEnable)
        {
            sendData << 20;
        }
        else
        {
            sendData << CurrentParagraph-1;
        }

        WriteData* writeData1 = new WriteData(58+(m_Index-1),sendData.size(),sendData);
        emit sig_AddWriteQueue(writeData1);

        //emit sig_SetWriteStartAddressAndRegisterCount(58+(m_Index-1),1,sendData);
        QTimer::singleShot(40,[=]()
        {
            if(writeData1 != nullptr)
                emit sig_AddWriteQueue(writeData1);
            //emit sig_SetWriteStartAddressAndRegisterCount(58+(m_Index-1),1,sendData);
        });
    }
    //    qDebug() << m_CurrentParagraph << "  " << m_CurrentParagraphEnable;
}

void FunctionForm::disableAllChildWidgets(QGroupBox *groupBox, bool isEnable)
{
    if (!groupBox)
        return;

    // 禁用QGroupBox本身
    groupBox->setEnabled(isEnable);

    // 遍历并禁用所有子控件
//    QObjectList children = groupBox->children();
//    for (QObject *child : children) {
//        if (QWidget *childWidget = qobject_cast<QWidget *>(child)) {
//            childWidget->setEnabled(isEnable);
//        }
//    }
}

//发送所有指令
void FunctionForm::SendRunCommand(bool isRunning)
{
    if(ui->btnMode_1->isChecked())//模式1
    {
        //0.先发送当前段落
        QList<quint16>  sendData0;
        if(m_CurrentParagraphEnable)
        {
            sendData0 << 20;
        }
        else
        {
            sendData0 << m_CurrentParagraph-1;
        }

        //段落数
        WriteData* writeData0 = new WriteData(58+(m_Index-1),sendData0.size(),sendData0);
        emit sig_AddWriteQueue(writeData0);

        //1.发送模式1电流
        QList<quint16>  sendData1;
        WriteData* writeData1 = nullptr;
        WriteData* writeData2 = nullptr;
        for (int i = 1;i <= 20;i++)
        {
            QDoubleSpinBox*  doubleSpinBox = this->findChild<QDoubleSpinBox*>(QString("doubleSpinBox_%1").arg(i));
            if(doubleSpinBox)
            {
                sendData1.append(floatToQuint16(doubleSpinBox->value()));
            }
        }
        if(sendData1.size() == 40)
        {
            writeData1 = new WriteData(100+((m_Index-1)*40),sendData1.size(),sendData1);
            emit sig_AddWriteQueue(writeData1);

            //emit sig_SetWriteStartAddressAndRegisterCount(100+((m_Index-1)*40),40,sendData1);
        }
        else
        {
            qDebug() << "浮点数转quint List错误";
        }

        //2.发送模式1时间
        QList<quint16> sendData2;
        for (int i = 1;i <= 20;i++)
        {
            TimeEditForm*  timeEditForm = this->findChild<TimeEditForm*>(QString("TimeEdit_%1").arg(i));
            if(timeEditForm)
            {
                sendData2 << quint32toQuint16List(  static_cast<quint32>(timeEditForm->value()));
            }
        }
        if(sendData2.size() == 40)
        {
            writeData2 = new WriteData(750+((m_Index-1)*40),sendData2.size(),sendData2);
            emit sig_AddWriteQueue(writeData2);
            //emit sig_SetWriteStartAddressAndRegisterCount(750+((m_Index-1)*40),40,sendData2);
        }
        else
        {
            qDebug() << "quint32转quint16 List错误";
        }

        //3.发送运行开始
        //此处1开0关
        //emit sig_SetRunState(false,m_Index);
        if(!isRunning)
            emit sig_SetRunState(true,m_Index);

        QTimer::singleShot(40,[=]()//第二次发送
                           {
                               //1.发送模式1电流
                               //emit sig_SetWriteStartAddressAndRegisterCount(100+((m_Index-1)*40),40,sendData1);
                               //2.发送模式1时间
                               //emit sig_SetWriteStartAddressAndRegisterCount(750+((m_Index-1)*40),40,sendData2);
                               //3.发送运行开始
                               //此处1开0关
                               //emit sig_SetRunState(false,m_Index);
                               //emit sig_SetRunState(true,m_Index);

                               //WriteData* writeData1 = new WriteData(100+((m_Index-1)*40),sendData1.size(),sendData1);
                               if(writeData0 != nullptr && writeData1 != nullptr && writeData2 != nullptr)
                               {
                                   emit sig_AddWriteQueue(writeData0);
                                   emit sig_AddWriteQueue(writeData1);
                                   emit sig_AddWriteQueue(writeData2);
                               }

                               //WriteData* writeData2 = new WriteData(750+((m_Index-1)*40),sendData2.size(),sendData2);

                           });
    }
    else if(ui->btnMode_2->isChecked())//模式2
    {
        //1.发送模式2起始电流
        double eleCurrent = ui->dSpinBox_startElecurrent->value();
        QList<quint16> sendData1;
        sendData1.append(floatToQuint16(eleCurrent));
        //emit sig_SetWriteStartAddressAndRegisterCount(1400+((m_Index-1)*2),2,sendData1);
        WriteData* writeData1 = new WriteData(1400+((m_Index-1)*2),sendData1.size(),sendData1);
        emit sig_AddWriteQueue(writeData1);

        //2.发送模式2开通时间
        quint32 startTime =  static_cast<quint32>( ui->TimeEditStart_21->value());
        QList<quint16> sendData2;
        sendData2.append(quint32toQuint16List(startTime));
        //emit sig_SetWriteStartAddressAndRegisterCount(2890+((m_Index-1)*2),2,sendData2);
        WriteData* writeData2 = new WriteData(2890+((m_Index-1)*2),sendData2.size(),sendData2);
        emit sig_AddWriteQueue(writeData2);

        //3.发送模式2关闭时间
        quint32 endTime =  static_cast<quint32>( ui->TimeEditEnd_22->value());
        QList<quint16> sendData3;
        sendData3.append(quint32toQuint16List(endTime));
        //emit sig_SetWriteStartAddressAndRegisterCount(2930+((m_Index-1)*2),2,sendData3);
        WriteData* writeData3 = new WriteData(2930+((m_Index-1)*2),sendData3.size(),sendData3);
        emit sig_AddWriteQueue(writeData3);

        //4.发送模式2循环次数
        quint32 Repetitions =  static_cast<quint32>( ui->spinBox_Repetitions->value());
        QList<quint16> sendData4;
        sendData4.append(quint32toQuint16List(Repetitions));
        //emit sig_SetWriteStartAddressAndRegisterCount(75+(m_Index-1),1,sendData4);
        WriteData* writeData4 = new WriteData(75+(m_Index-1),sendData4.size(),sendData4);
        emit sig_AddWriteQueue(writeData4);

        //5.发送模式2开始运行
        //此处1开0关
        //emit sig_SetRunState(false,m_Index);
        if(!isRunning)
            emit sig_SetRunState(true,m_Index);
        QTimer::singleShot(40,[=]()//第二次发送
                           {
                               //emit sig_SetWriteStartAddressAndRegisterCount(1400+((m_Index-1)*2),2,sendData1);
                               //emit sig_SetWriteStartAddressAndRegisterCount(2890+((m_Index-1)*2),2,sendData2);
                               //emit sig_SetWriteStartAddressAndRegisterCount(2930+((m_Index-1)*2),2,sendData3);
                               //emit sig_SetWriteStartAddressAndRegisterCount(75+(m_Index-1),1,sendData4);

                               if( writeData1 != nullptr && writeData2 != nullptr && writeData3 != nullptr && writeData4 != nullptr)
                               {
                                   emit sig_AddWriteQueue(writeData1);
                                   emit sig_AddWriteQueue(writeData2);
                                   emit sig_AddWriteQueue(writeData3);
                                   emit sig_AddWriteQueue(writeData4);
                                   //此处1开0关
                                   //emit sig_SetRunState(false,m_Index);
                                   if(!isRunning)
                                       emit sig_SetRunState(true,m_Index);
                               }
                           });
    }
    else if(ui->btnMode_3->isChecked())//模式3
    {
        //1.发送模式3电流
        QList<quint16>  sendData1;
        WriteData* writeData1 = nullptr;
        WriteData* writeData2 = nullptr;
        WriteData* writeData3 = nullptr;
        WriteData* writeData4 = nullptr;
        WriteData* writeData5 = nullptr;
        WriteData* writeData6 = nullptr;

        for (int i = 1;i <= 20;i++)
        {
            QDoubleSpinBox*  doubleSpinBox = this->findChild<QDoubleSpinBox*>(QString("doubleSpinBox_%1").arg(i));
            if(doubleSpinBox)
                sendData1.append(floatToQuint16(doubleSpinBox->value()));
        }
        if(sendData1.size() == 40)
        {
            writeData1 = new WriteData(2150+((m_Index-1)*40),sendData1.size(),sendData1);
            emit sig_AddWriteQueue(writeData1);
            //emit sig_SetWriteStartAddressAndRegisterCount(2150+((m_Index-1)*40),40,sendData1);
        }
        else
            qDebug() << "浮点数转quint List错误";

        //2.发送模式3时间
        QList<quint16> sendData2;
        for (int i = 1;i <= 20;i++)
        {
            TimeEditForm*  timeEditForm = this->findChild<TimeEditForm*>(QString("TimeEdit_%1").arg(i));
            if(timeEditForm)
                sendData2 << quint32toQuint16List(  static_cast<quint32>(timeEditForm->value()));
        }
        if(sendData2.size() == 40)
        {
            //emit sig_SetWriteStartAddressAndRegisterCount(1500+((m_Index-1)*40),40,sendData2);
            writeData2 = new WriteData(1500+((m_Index-1)*40),sendData2.size(),sendData2);
            emit sig_AddWriteQueue(writeData2);
        }
        else
            qDebug() << "quint32转quint16 List错误";


        //3.发送开通时间
        quint32 startTime =  static_cast<quint32>( ui->TimeEditStart_21->value());
        QList<quint16> sendData3;
        sendData3.append(quint32toQuint16List(startTime));
        //emit sig_SetWriteStartAddressAndRegisterCount(2962+((m_Index-1)*2),2,sendData3);
        writeData3 = new WriteData(2962+((m_Index-1)*2),sendData3.size(),sendData3);
        emit sig_AddWriteQueue(writeData3);


        //4.发送关闭时间
        quint32 endTime =  static_cast<quint32>( ui->TimeEditEnd_22->value());
        QList<quint16> sendData4;
        sendData4.append(quint32toQuint16List(endTime));
        //emit sig_SetWriteStartAddressAndRegisterCount(2994+((m_Index-1)*2),2,sendData4);
        writeData4 = new WriteData(2994+((m_Index-1)*2),sendData4.size(),sendData4);
        emit sig_AddWriteQueue(writeData4);


        //5.发送循环次数
        quint32 Repetitions =  static_cast<quint32>( ui->spinBox_Repetitions->value());
        QList<quint16> sendData5;
        sendData5.append(quint32toQuint16List(Repetitions));
        //emit sig_SetWriteStartAddressAndRegisterCount(3026+(m_Index-1),1,sendData5);
        writeData5 = new WriteData(3026+(m_Index-1),sendData5.size(),sendData5);
        emit sig_AddWriteQueue(writeData5);


        //6.发送开通电压 即起始电流
        double eleCurrent =  ui->dSpinBox_startElecurrent->value();
        QList<quint16> sendData6;
        sendData6.append(floatToQuint16(eleCurrent));
        //emit sig_SetWriteStartAddressAndRegisterCount(3050+((m_Index-1)*2),2,sendData6);
        writeData6 = new WriteData(3050+((m_Index-1)*2),sendData6.size(),sendData6);
        emit sig_AddWriteQueue(writeData6);


        //7.发送运行开始
        //此处1开0关
        if(!isRunning)
            emit sig_SetRunState(true,m_Index);

        //第二次发送
        QTimer::singleShot(40,[=](){
            //6.发送模式
            /*
               emit sig_SetWriteStartAddressAndRegisterCount(2150+((m_Index-1)*40),40,sendData1);
               emit sig_SetWriteStartAddressAndRegisterCount(1500+((m_Index-1)*40),40,sendData2);
               emit sig_SetWriteStartAddressAndRegisterCount(2962+((m_Index-1)*2),2,sendData3);
               emit sig_SetWriteStartAddressAndRegisterCount(2994+((m_Index-1)*2),2,sendData4);
               emit sig_SetWriteStartAddressAndRegisterCount(3026+(m_Index-1),1,sendData5);
               emit sig_SetWriteStartAddressAndRegisterCount(3050+((m_Index-1)*2),2,sendData6);
               */
            if(writeData1 != nullptr && writeData2 != nullptr && writeData3 != nullptr &&
                writeData4 != nullptr && writeData5 != nullptr && writeData6 != nullptr)
            {
                emit sig_AddWriteQueue(writeData1);
                emit sig_AddWriteQueue(writeData2);
                emit sig_AddWriteQueue(writeData3);
                emit sig_AddWriteQueue(writeData4);
                emit sig_AddWriteQueue(writeData5);
                emit sig_AddWriteQueue(writeData6);
            }
            //此处1开0关
            if(!isRunning)
                emit sig_SetRunState(true,m_Index);
        });
    }
    else
    {
        QMessageBox msgBox;
        msgBox.setWindowTitle("提示");
        msgBox.setText("请选择一个模式");
        msgBox.setIcon(QMessageBox::Information);

        // 创建 OK 和 Cancel 按钮
        QPushButton *okButton = msgBox.addButton("OK", QMessageBox::AcceptRole);
        //        QPushButton *cancelButton = msgBox.addButton("Cancel", QMessageBox::RejectRole);

        // 设置按钮大小
        QSize buttonSize(60, 30); // 宽度60，高度30
        okButton->setFixedSize(buttonSize);
        //        cancelButton->setFixedSize(buttonSize);

        // 执行消息框并获取结果
        int ret = msgBox.exec();

        // 根据用户的选择执行操作
        if (ret == QMessageBox::AcceptRole) {
            // 用户点击了 OK 按钮
            // 这里可以放置退出程序的代码
            return;
        }
    }
}


//运行按钮按下
void FunctionForm::on_btnRun_clicked()
{
    if(isRunState)//当前是运行中
    {

        emit sig_SetRunState(false,m_Index);
        //emit sig_SetRunState(true,m_Index);
    }
    else //当前是停止运行，即将运行
    {
        SendRunCommand();
    }
}


void FunctionForm::on_btnMode_1_clicked()
{
    m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
    m_CurrentMode = 1;
    m_Settings->setValue("CurrentMode",m_CurrentMode);
    m_Settings->endGroup();

    QList<quint16> sendData1;
    sendData1 << 1;//设置模式为1
    //emit sig_SetWriteStartAddressAndRegisterCount(3300+(m_Index-1),1,sendData1);
    WriteData* writeData = new WriteData(3300+(m_Index-1),sendData1.size(),sendData1);
    emit sig_AddWriteQueue(writeData);
    QTimer::singleShot(40,[=]()
    {
        //emit sig_SetWriteStartAddressAndRegisterCount(3300+(m_Index-1),1,sendData1);
        if(writeData != nullptr)
            emit sig_AddWriteQueue(writeData);
    });

}

void FunctionForm::on_btnMode_2_clicked()
{
    m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
    m_CurrentMode = 2;
    m_Settings->setValue("CurrentMode",m_CurrentMode);
    m_Settings->endGroup();


    QList<quint16> sendData1;
    sendData1 << 2;//设置模式为2
    //emit sig_SetWriteStartAddressAndRegisterCount(3300+(m_Index-1),1,sendData1);
    WriteData* writeData = new WriteData(3300+(m_Index-1),sendData1.size(),sendData1);
    QTimer::singleShot(40,[=]()
    {
        //emit sig_SetWriteStartAddressAndRegisterCount(3300+(m_Index-1),1,sendData1);
        if(writeData != nullptr)
            emit sig_AddWriteQueue(writeData);
    });
}

void FunctionForm::on_btnMode_3_clicked()
{
    m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
    m_CurrentMode = 3;
    m_Settings->setValue("CurrentMode",m_CurrentMode);
    m_Settings->endGroup();

    QList<quint16> sendData1;
    sendData1 << 3;//设置模式为3
    //emit sig_SetWriteStartAddressAndRegisterCount(3300+(m_Index-1),1,sendData1);
    WriteData* writeData = new WriteData(3300+(m_Index-1),sendData1.size(),sendData1);
    QTimer::singleShot(40,[=]()
    {
        //emit sig_SetWriteStartAddressAndRegisterCount(3300+(m_Index-1),1,sendData1);
        if(writeData != nullptr)
            emit sig_AddWriteQueue(writeData);
    });
}

/*
void FunctionForm::on_doubleSpinBoxCurValue_valueChanged(double arg1)
{
    // 指定要读取的组 模式一的数据
    m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
    m_Settings->setValue("EleCurrentRange",arg1);
    // 结束组的读取
    m_Settings->endGroup();
}
*/

//关闭子界面前先切换焦点
void FunctionForm::slot_SubFormClose()
{
    this->setFocus();
}

//定时器槽函数
void FunctionForm::timeoutWatchDog()
{
    float fCurrent = ui->doubleSpinBox_EleCur->value();
    float fVoltage = ui->doubleSpinBox_EleVol->value();
    QString   lineStr = "\t"+QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss.zzz")+"\t,"
            + QString::number(fCurrent,'f',2) + ","
            + QString::number(fVoltage,'f',2);
    //qDebug() << lineStr << " m_Index_:" << m_Index;
    lineStr+= "\n";
    *m_Out <<  lineStr;
    m_WaveForm->setCurVolValue(fCurrent,fVoltage);

}

//故障延迟的数据
void FunctionForm::timeoutWatchDog_delay()
{
    //记录十次
    ++m_CSV_delay;
    if(m_CSV_delay == 10)
    {
        m_CSV_delay = 0;
        m_timer_CSV_delay->stop();
    }

    float fCurrent = ui->doubleSpinBox_EleCur->value();
    float fVoltage = ui->doubleSpinBox_EleVol->value();
    QString   lineStr = "\t"+QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss.zzz")+"\t,"
            + QString::number(fCurrent,'f',2) + ","
            + QString::number(fVoltage,'f',2) + QString(tr(",故障数据"));
    //qDebug() << lineStr << " m_Index_:" << m_Index;
    lineStr+= "\n";
    *m_Out <<  lineStr;
    m_WaveForm->setCurVolValue(fCurrent,fVoltage);
}

/*
void FunctionForm::on_btnEleCurCSV_clicked(bool checked)
{
    if(isConState)
    {
        if(ui->btnEleVolCSV->isChecked() || checked)
        {
            if(!m_timer_CSV->isActive())
                m_timer_CSV->start(1000);
            return;
        }
        else
        {
           if(m_timer_CSV->isActive())
               m_timer_CSV->stop();
            return;
        }
    }
}

void FunctionForm::on_btnEleVolCSV_clicked(bool checked)
{
    if(isConState)//连接状态
    {
        if(ui->btnEleCurCSV->isChecked() || checked)
        {
            if(!m_timer_CSV->isActive())
                m_timer_CSV->start(1000);
            return;
        }
        else
        {
            if(m_timer_CSV->isActive())
                m_timer_CSV->stop();
            return;
        }
    }
}
*/

void FunctionForm::on_btnMode_1_pressed()
{
    if(isRunState)
    {
        QString InfoStr;
        switch (m_CurrentMode) {
        case 2:
            InfoStr = QString("当前模式2正在运行，是否关闭模式2切换到模式1？");
            break;
        case 3:
            InfoStr = QString("当前模式3正在运行，是否关闭模式3切换到模式1？");
            break;
        default:
            return;
            break;
        }

        msgBox.setText(InfoStr);
        // 执行消息框并获取结果
        int ret = msgBox.exec();

        // 根据用户的选择执行操作
        if (ret == QMessageBox::AcceptRole) {
            // 用户点击了 OK 按钮
            // 这里可以放置退出程序的代码
            emit sig_SetRunState(true,m_Index);//停用当前运行
            ui->btnMode_1->setChecked(true);
            on_btnMode_1_clicked();

            QTimer::singleShot(300,[=]()//等线程退出关闭
            {
                on_btnRun_clicked();
            });

        } else {
            // 用户点击了 Cancel 按钮
            // 继续程序的执行
            switch (m_CurrentMode) {
            case 2:
                ui->btnMode_2->setChecked(true);
                break;
            case 3:
                 ui->btnMode_3->setChecked(true);
                break;
            default:
                break;
            }
            return;
        }


    }
}

void FunctionForm::on_btnMode_2_pressed()
{
    if(isRunState)
    {
        QString InfoStr;
        switch (m_CurrentMode) {
        case 1:
            InfoStr = QString("当前模式1正在运行，是否关闭模式1切换到模式2？");
            break;
        case 3:
            InfoStr = QString("当前模式3正在运行，是否关闭模式1切换到模式2？");
            break;
        default:
            return;
            break;
        }

        msgBox.setText(InfoStr);
        // 执行消息框并获取结果
        int ret = msgBox.exec();

        // 根据用户的选择执行操作
        if (ret == QMessageBox::AcceptRole) {
            // 用户点击了 OK 按钮
            // 这里可以放置退出程序的代码
            emit sig_SetRunState(true,m_Index);//停用当前运行
            ui->btnMode_2->setChecked(true);
            on_btnMode_2_clicked();
            QTimer::singleShot(300,[=]()
            {
                on_btnRun_clicked();
            });

        } else {
            // 用户点击了 Cancel 按钮
            // 继续程序的执行
            switch (m_CurrentMode) {
            case 1:
                ui->btnMode_1->setChecked(true);
                break;
            case 3:
                 ui->btnMode_3->setChecked(true);
                break;
            default:
                break;
            }
            return;
        }
    }
}

void FunctionForm::on_btnMode_3_pressed()
{
    if(isRunState)
    {
        QString InfoStr;
        switch (m_CurrentMode) {
        case 1:
            InfoStr = QString("当前模式1正在运行，是否关闭模式1切换到模式3？");
            break;
        case 2:
            InfoStr = QString("当前模式2正在运行，是否关闭模式2切换到模式3？");
            break;
        default:
            return;
            break;
        }

        msgBox.setText(InfoStr);


        // 执行消息框并获取结果
        int ret = msgBox.exec();

        // 根据用户的选择执行操作
        if (ret == QMessageBox::AcceptRole) {
            // 用户点击了 OK 按钮
            // 这里可以放置退出程序的代码
            emit sig_SetRunState(true,m_Index);//停用当前运行
            ui->btnMode_3->setChecked(true);
            on_btnMode_3_clicked();
            QTimer::singleShot(300,[=]()
            {
                on_btnRun_clicked();
            });

        } else {
            // 用户点击了 Cancel 按钮
            // 继续程序的执行
            switch (m_CurrentMode) {
            case 1:
                ui->btnMode_1->setChecked(true);
                break;
            case 3:
                 ui->btnMode_3->setChecked(true);
                break;
            default:
                break;
            }
            return;
        }
    }
}

void FunctionForm::on_btn_Link_clicked()
{
    emit sig_openIPSet(true);
}

/*
//电压存Ini
void FunctionForm::on_doubleSpinBoxVolValue_valueChanged(double arg1)
{
    // 指定要读取的组 模式一的数据
    m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
    m_Settings->setValue("EleVolRange",arg1);
    // 结束组的读取
    m_Settings->endGroup();
}
*/

//电压超值设置
void FunctionForm::on_btnVolValue_clicked()
{
    m_eleVolRange = ui->doubleSpinBoxVolValue->value();
    //1.发送超值的电流
    QList<quint16> sendData1;
    sendData1.append(floatToQuint16(m_eleVolRange));

    WriteData* writeData1 = new WriteData(3202+((m_Index-1)*2),sendData1.size(),sendData1);
    emit sig_AddWriteQueue(writeData1);

    //emit sig_SetWriteStartAddressAndRegisterCount(3170+((m_Index-1)*2),2,sendData1);
    QTimer::singleShot(40,[=]()
    {
        if(writeData1 != nullptr)
            emit sig_AddWriteQueue(writeData1);
        //emit sig_SetWriteStartAddressAndRegisterCount(3170+((m_Index-1)*2),2,sendData1);
    });

    m_Settings->beginGroup(QString("Power%1_Other").arg(m_Index));
    m_Settings->setValue("EleVolRange",m_eleVolRange);
    m_Settings->endGroup();
}

//复位按钮
void FunctionForm::on_btnReset_clicked()
{
    emit sig_Reset(m_Index);
}
//总复位按钮
void FunctionForm::on_btnReset_2_clicked()
{
    emit sig_GeneralReset();//发送总复位
}

//运行时 更新参数
void FunctionForm::on_btnUpdate_clicked()
{
    SendRunCommand(true);//运行中修改参数
}

